package com.fzfnn.scrapbook.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class EmailUtil {

    private static String SMTP_HOST;
    private static String FROM_EMAIL;
    private static String AUTH_CODE;

    @Value("${spring.mail.host}")
    private String smtpHost;
    @Value("${spring.mail.username}")
    private String fromEmail;
    @Value("${spring.mail.password}")
    private String authCode;

    // 多线程池
    private static final ExecutorService executor = Executors.newFixedThreadPool(5);

    // 将非 static 的值赋给 static 变量
    @PostConstruct
    public void init() {
        SMTP_HOST = smtpHost;
        FROM_EMAIL = fromEmail;
        AUTH_CODE = authCode;
    }

    public static void sendEmail(String toEmail, String subject, String content) {
        executor.submit(() -> {
            try {
                Properties props = new Properties();
                props.put("mail.smtp.host", SMTP_HOST);
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.port", "465");
                props.put("mail.smtp.ssl.enable", "true");

                Session session = Session.getInstance(props, new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(FROM_EMAIL, AUTH_CODE);
                    }
                });

                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(FROM_EMAIL));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
                message.setSubject(subject);
                message.setText(content);
                Transport.send(message);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        });
    }
}
